/*
		ServEngine framework library
		A library to fast develop JEE online applications
	
		Copyright 2008 José Ignacio de Córdoba Álvaro

		Licensed under the Apache License, Version 2.0 (the "License");
		you may not use this file except in compliance with the License.
		You may obtain a copy of the License at

				http://www.apache.org/licenses/LICENSE-2.0

		Unless required by applicable law or agreed to in writing, software
		distributed under the License is distributed on an "AS IS" BASIS,
		WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
		See the License for the specific language governing permissions and
		limitations under the License.
	
		Jose Ignacio de Cordoba Alvaro
		http://ignacio.decordoba.com
*/

package com.servengine.log;

import java.util.Date;

import java.util.HashMap;
import java.util.List;

import java.util.Map;

import javax.ejb.Stateless;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless(name="LogManager")
public class LogManagerBean implements LogManagerLocal
{
	@PersistenceContext(unitName="mainPersistenceUnit")
	private EntityManager entityManager;

	public void log(String portalid, Integer userId, String module, String action, String method, String data, String ipaddress)
	{
		entityManager.persist(new LogEntry(portalid,userId,module,action,method,data,ipaddress));
	}

	public List<LogEntry> getEntries(String portalid, Integer userId, String module, String action, String methodName, Date from, Date to, String data, int maxResults)
	{
	  Map<String, Object> parameters=new HashMap<String, Object>(); //Hay que añadirlos al final, no se pueden ir añadiendo confirme se comprueba
	  String hql="select o from LogEntry o where o.portalid = :portalid"; //order by o.date
	  parameters.put("portalid", portalid);
	  if (userId!=null)
	  {
	    hql+=" and o.userId = :userId";
	    parameters.put("userId", userId);
	  }
	  if (module!=null && !module.equals(""))
	  {
	    hql+=" and o.module = :module";
	    parameters.put("module", module);
	  }
	  if (action!=null && !action.equals(""))
	  {
	    hql+=" and o.action = :action";
	    parameters.put("action", action);
	  }
	  if (methodName!=null && !methodName.equals(""))
	  {
	    hql+=" and o.methodName = :methodName";
	    parameters.put("methodName", methodName);
	  }
	  if (from!=null)
	  {
	    hql+=" and o.date >= :from";
	    parameters.put("from", from);
	  }
	  if (to!=null)
	  {
	    hql+=" and o.date <= :to";
	    parameters.put("to", to);
	  }
	  if (data!=null&&data.length()>0)
	  {
	    hql+=" and lower(o.data) like :data";
	    parameters.put("data", "%"+data.toLowerCase()+"%");
	  }
	  Query query=entityManager.createQuery(hql+" order by o.date");
	  if (maxResults>0)
			query.setMaxResults(maxResults);
	  for (String key: parameters.keySet())
	    query.setParameter(key, parameters.get(key));
	  return query.getResultList();
	}
}
